﻿using System;

namespace Pyramid.Tools
{
	public class Code34
	{
		private static int _nextCirclingSeq;
		private static long _currentSeconds;
		private static readonly object Synclock = new object();

		/// <summary>
		///     获取基于时间和循环码的代码串，支撑每秒4千万次
		///     取ISO时间（1970-1-1）的秒数 7 位代码 + 5 位循环码，共12个字符
		/// </summary>
		/// <returns></returns>
		public static string NextCode()
		{
			lock (Synclock)
			{
				var seconds = (long) (DateTime.Now - DateTime.Parse("1970-1-1")).TotalSeconds;
				if (_currentSeconds != seconds)
				{
					_currentSeconds = seconds;
					_nextCirclingSeq = 0;
				}
				else
				{
					_nextCirclingSeq++;
				}
				return GetCode(seconds, 7) + GetCode(_nextCirclingSeq, 5);
			}
		}

		/// <summary>
		///     将整型转换成类似车牌的代码串
		/// </summary>
		/// <param name="num">要转换的整型</param>
		/// <param name="length">最终代码串长度</param>
		/// <returns></returns>
		public static string GetCode(long num, int length)
		{
			const string str = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
			var level = Math.Ceiling(Math.Log(num, str.Length));
			var code = "";
			for (var i = 0; i < level; ++i)
			{
				code = str[(int) (num%str.Length)] + code;
				num = num/str.Length;
			}
			if (num != 0)
			{
				code = string.Format("{0}{1}", num, code);
			}
			return code.PadLeft(length, '0');
		}
	}
}